/**
 * @(#)client.java
 *
 *
 * @author 
 * @version 1.00 2014/2/28
 */
import java.io.*;
import java.net.*;
import java.awt.*;
import java.util.*;   
import javax.swing.*;
import java.awt.event.*;
import javax.sound.sampled.*;

public class client {
        
    private InetAddress inetaddress;
    private String address=null;
    private Socket socket=null;
    private String message=null;
    private JOptionPane optionpane;
    private PrintWriter lineout;
    private JTextArea textarea;
    private JFrame frame;
    private JTextField textfield;
    private String name="Client";
    private JButton downloadButton;
    private JButton uploadButton;
    private JButton chatButton;
  	private double duration,second;
  	private String errStr;
  	int bufSize = 16384;
    private static boolean record=false;
    private TargetDataLine line;
    private int UserConnectionPointer=1;
    private JFileChooser filechoose;
    private File file;
    private StringTokenizer stringtokenizer;
    private String file_info = null;
    private boolean download = false;
    private boolean upload = false;
    private BufferedReader inline;
    public client() {
    	
    	System.out.println("running client..");
    	name = optionpane.showInputDialog(new JFrame(),"Enter your name");
    	message = optionpane.showInputDialog(new JFrame(),"Enter the servers local address","fe80:0:0:0:3d4c:f171:c327:d8bb%23");
    	connect();
    	
    }
    public void connect(){
    
    	try{
    		socket = new Socket(message,3333);
            address = message;
            System.out.println("client socket: "+ socket);
    		inline = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    		lineout = new PrintWriter(socket.getOutputStream(), true);
    		showGui();
    		System.out.print("initialize actionlistener");
    		Actionlistener();
            while((message=inline.readLine())!=null){
                    System.out.println("current message: "+message);

                    //check messagees before appending in the textarea
                    if(message.equals("null")){
                        System.out.println("null message");
                       message="";
                    }
                    
                    if(message.equals(name+":play")){
                        System.out.println("playing audio..");
                        new Thread(new Playback()).start();
                        }
                    else if(message.equals("downloadfile")){
                        System.out.println("downloadfile request");
                        message="";
                        file_info = inline.readLine();
                         new Thread(new downloadFile()).start();
                        
                    }
                    message.trim();
                    textarea.append(message+'\n');

                   

            //       if(message.equals(name+":file")){
              //          System.out.println("choose a file..");
                //        fileChooser();
                  //      return;
                  
                }

    	}
        catch (Exception e){
    		System.out.println("connection error "+e +" message " + message);
            // create anoher runnable class with diffrent port  for file upload/download
    		//System.exit(0);
    	}
    	
    }
    public void showGui(){
    	System.out.println("initialize Gui");
    		textarea = new JTextArea();
    		textfield = new JTextField();
    		frame = new JFrame("Client");
    		frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
    		downloadButton = new JButton("add file");
            chatButton = new JButton("Chat");
            uploadButton = new JButton("Upload");
            frame.setLayout(new GridLayout(2,1));
            JPanel panel = new JPanel();
            System.out.println("adding panel component");
            panel.add(downloadButton);
            panel.add(uploadButton);
            panel.add(chatButton);  	
            System.out.println("adding panel");
    		frame.add(panel);
            JPanel panel2 = new JPanel();
            panel2.setLayout(new GridLayout(2,1));
    		panel2.add(new JScrollPane(textarea));
    		panel2.add(textfield);
            frame.add(panel2);
    		frame.setSize(300,390);
    		frame.setVisible(true);
    }
  
    public void Actionlistener(){
    		textfield.addActionListener(new ActionListener(){
      		    public void actionPerformed(ActionEvent event) {
                    lineout.println(name+":" + ((String)textfield.getText()));
                    lineout.println(UserConnectionPointer);
        		    textfield.setText("");
     			    }
                });

             uploadButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                System.out.println("uploadButton listener");
                try{
					 int retrnValue = filechoose.showOpenDialog(null);
           			 if (retrnValue == JFileChooser.APPROVE_OPTION) {
                		file = filechoose.getSelectedFile();
            			}
                 new Thread(new uploadFile()).start();
                }
                catch (Exception e){
                    System.out.println("uploadButton action listener error "+ e);
                    }       
                }  
            });
             downloadButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                System.out.println("downloadButton listener");
                try{

                    //System.out.println("starting uploadfile class..");
                   // new Thread(new uploadFile()).start();
                lineout.println("downloadfile");// sends the desired filename
                System.out.println("Sending UserConnectionPointer");
                lineout.println(UserConnectionPointer);

                lineout.println("mychoosenfileisblahlblah");
                }
              catch (Exception e){
                    System.out.println("action listener error "+ e);
                    }   
                }
            });

    public class uploadFile implements Runnable{ // upload file
        public void run(){
        try {

           UserConnectionPointer=1;
          //  if(UserConnectionPointer!=0){

                int port=0;
                System.out.println("getting local port");
                port = socket.getLocalPort();
             
        
                System.out.println("Sending signal");
                lineout.println("uploadFile");
                lineout.println(UserConnectionPointer);
              

                long filesize;
                filesize = file.length();

                lineout.println(file.getName()+","+filesize+","
                                +UserConnectionPointer+","+socket.getLocalPort());

                Socket filesocket;

                filesocket = new Socket(address,1233);

               // UserConnectionPointer=0;//temporary 

        

                System.out.println("new file copy..."); 
                System.out.println("waiting for receiver.....");
                System.out.println("Accepted connection : " + socket);
            
                byte [] bytearray  = new byte [(int)file.length()];

                FileInputStream fin = new FileInputStream(file);

                BufferedInputStream bin = new BufferedInputStream(fin);
        
                bin.read(bytearray,0,bytearray.length);
                OutputStream os = filesocket.getOutputStream();
                System.out.println("Sending File...");
                os.write(bytearray,0,bytearray.length);
                os.flush();
                filesocket.close();
                System.out.println("File upload complete");
                }
    // if con=0 ..   }
            catch (IOException e) {
               System.out.println("Sending file error: " +e);    
        }
        }
    } // end of uploadFile class  
    public  class  downloadFile implements Runnable{
        public void run(){
        try{

             
            System.out.println("getting file info...");
            int filesize;
            int bytesRead;
            int currentTot = 0;
            String file_information=null;
            int port = 0;
            file_information = file_info; // temporary
            System.out.println("Sending signal");
            String filename;
            
            
            System.out.println("setting StringTokenizer");
           
            stringtokenizer = new StringTokenizer(file_information.trim(),",");
            System.out.println("file info: " + file_information);
              
            filename = stringtokenizer.nextToken();
            System.out.println("getting filename: " + file_information);

            filesize = Integer.parseInt(stringtokenizer.nextToken());

            UserConnectionPointer = Integer.parseInt(stringtokenizer.nextToken());
            port = Integer.parseInt(stringtokenizer.nextToken());

            port = 2222; // for the mean time only.. 

        
            Socket fileDownloadSocket = new Socket(address,port); 

            System.out.println("userConnectionPointer: "+UserConnectionPointer);

               
            System.out.println("file socket " + fileDownloadSocket);
                
            filesize= filesize*2;
            byte [] bytearray  = new byte [filesize];
            InputStream is = fileDownloadSocket.getInputStream();
            FileOutputStream fos = new FileOutputStream(filename);
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            bytesRead = is.read(bytearray,0,bytearray.length);
            currentTot = bytesRead;
            System.out.println("reading input");

            do {
               bytesRead =
               is.read(bytearray, currentTot, (bytearray.length-currentTot));
               if(bytesRead >= 0) currentTot += bytesRead;
                } while(bytesRead > -1);

                bos.write(bytearray, 0 , currentTot);
                bos.flush();
                bos.close();
                is.close();
                fileDownloadSocket.close();
                System.out.println("file download complete "+ filename);
                }
                catch (Exception e){
                   System.out.println("file download file error: "+ e);
                   download=false;
                }
            } 
        }           
    public static void main(String[] args) {
        new client();
    }
}
